/**
 * 
 */
package com.project.solomon.MBean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.RandomStringUtils;
import org.primefaces.event.FileUploadEvent;

import com.project.entity.Account;
import com.project.entity.Property;
import com.project.entity.Property_Image;

import com.project.solomon.SessionBean.PropertyBeanRemote;
import com.project.util.MessageCall;

/**
 * @author Solomon
 * 
 */
@ManagedBean(name = "updatePropertyBean")
@SessionScoped
public class UpdatePropertyBean {

	private Property prop;

	private Account currentAccount;

	private String pid;
	private String propType;
	@SuppressWarnings("unused")
	private String initResult;

	
	private boolean owner = false;

	
	private List propImageList;
	private List propImageListLink;
	private String deleteLink;
	private List propImageListObject;
	private List prop_img;
	public UpdatePropertyBean() throws Exception {
		prop = new Property();
		this.prop_img = new ArrayList();
		getInitResult();
	}

	public List getProp_img() {
		return prop_img;
	}

	public void setProp_img(List prop_img) {
		this.prop_img = prop_img;
	}

	
	/**
	 * @param propImageListObject the propImageListObject to set
	 */
	public void setPropImageListObject(List propImageListObject) {
		this.propImageListObject = propImageListObject;
	}

	/**
	 * @return the propImageListObject
	 */
	public List getPropImageListObject() {
		return propImageListObject;
	}

	/**
	 * @param deleteLink the deleteLink to set
	 */
	public void setDeleteLink(String deleteLink) {
		this.deleteLink = deleteLink;
	}

	/**
	 * @return the deleteLink
	 */
	public String getDeleteLink() {
		return deleteLink;
	}

	/**
	 * @param propImageListLink the propImageListLink to set
	 */
	public void setPropImageListLink(List propImageListLink) {
		this.propImageListLink = propImageListLink;
	}

	/**
	 * @return the propImageListLink
	 */
	public List getPropImageListLink() {
		return propImageListLink;
	}

	/**
	 * @param propImageList the propImageList to set
	 */
	public void setPropImageList(List propImageList) {
		this.propImageList = propImageList;
	}

	/**
	 * @return the propImageList
	 */
	public List getPropImageList() {
		return propImageList;
	}

	public void setInitResult(String initResult) {
		this.initResult = initResult;
	}

	public String getInitResult() throws Exception {
		InitialContext ctx = new InitialContext();
		PropertyBeanRemote propRe = (PropertyBeanRemote) ctx
				.lookup("MySweetHome/PropertyBean/remote");
		List<Property> result = propRe.requestProperty(getPid());
		initListImages(getPid());
		if (result.size() > 0) {
			this.prop = result.get(0);
			return "success";
		} else
			return "notfound";

	}

	public void setProp(Property prop) {
		this.prop = prop;
	}

	public Property getProp() throws Exception {
		return prop;
	}

	public void setPid(String pid) {
		this.pid = pid;
	}

	public String getPid() {
		return pid;
	}

	public void setPropType(String propType) {
		this.propType = propType;
	}

	public String getPropType() {
		propType = getPid().substring(0, 1).toLowerCase().trim();
		return propType;
	}

	public void setCurrentAccount(Account currentAccount) {
		this.currentAccount = currentAccount;
	}

	public Account getCurrentAccount() {
		HttpServletRequest req = (HttpServletRequest) FacesContext
				.getCurrentInstance().getExternalContext().getRequest();
		Object obj = req.getSession().getAttribute("mAccount");
		currentAccount = ((com.project.tructc.MBean.MAccount) obj).getAcc();
		return currentAccount;
	}

	public void setOwner(boolean owner) {
		this.owner = owner;
	}

	public boolean isOwner() {
		if (prop.getAccount().getAccID() == currentAccount.getAccID())
			owner = true;
		else
			owner = false;

		return owner;
	}

	public String updateProperty() throws Exception {

		InitialContext ctx = new InitialContext();
		PropertyBeanRemote propRe = (PropertyBeanRemote) ctx
				.lookup("MySweetHome/PropertyBean/remote");

		FacesContext context = FacesContext.getCurrentInstance();
		
		boolean check = propRe.updateProperty(this.prop);
		//this.insertImagesToList(this.prop);

		
		if (check) {
			context.addMessage(null, new FacesMessage(
					FacesMessage.SEVERITY_INFO, "Successful",
					"Update Sucessful!"));
			return "ok";
		} else {
			context.addMessage(null, new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Error", "Update failed"));
			return "failed";
		}
	}

	public String redirectUpdate() {
		if (pid != null) {
			return "redirect";
		} else {
			return "notfound";
		}
	}
	
	public void initListImages(String pid) throws NamingException, SecurityException, IOException
	{
		this.propImageList = new ArrayList();
		this.propImageListLink = new ArrayList();
		this.propImageListObject = new ArrayList();
		InitialContext ctx = new InitialContext();
		PropertyBeanRemote propRe = (PropertyBeanRemote) ctx
				.lookup("MySweetHome/PropertyBean/remote");
		ExternalContext extContext = FacesContext.getCurrentInstance()
		.getExternalContext();
	
		List result = propRe.requestPropertyImages(pid);
		if(result.size() != 0)
		{
			Iterator ite = result.iterator();
			while(ite.hasNext())
			{
				Property_Image image = (Property_Image)ite.next();
				String imagePathString = image.getPath();
				File temp = new File(extContext.getRealPath(imagePathString));
				this.propImageList.add(temp);
				this.propImageListLink.add(imagePathString);
				this.propImageListObject.add(image);
			}
		}
		
	}
	
	public void deleteImage() throws NamingException, SecurityException, IOException
	{
		InitialContext ctx = new InitialContext();
		PropertyBeanRemote propRe = (PropertyBeanRemote) ctx
				.lookup("MySweetHome/PropertyBean/remote");
		
			Iterator ite = this.propImageListLink.iterator();
			int i = 0;
			while(ite.hasNext())
			{
				String tempImage = (String)ite.next();
				if(this.deleteLink.equals(tempImage))
				{
					File temp = (File)this.propImageList.get(i);
					if(temp.exists())
					{
						temp.delete();
					}
					ite.remove();
					this.propImageList.remove(i);
					Property_Image deleteImageObject = (Property_Image)this.propImageListObject.get(i);
					propRe.deletePropImage(deleteImageObject);
					this.propImageListObject.remove(i);
					
					
					
				}
				i++;
			}
		
		if(this.prop_img.size() > 0)
		{
			Iterator ite2 = this.prop_img.iterator();
			while(ite2.hasNext())
			{
				Property_Image p_i_temp = (Property_Image)ite2.next();
				if(p_i_temp.getPath().equalsIgnoreCase(deleteLink))
				{
					ite2.remove();
				}
			}
		}
		

	}
	
	@SuppressWarnings("unchecked")
	public void handleFileUpload(FileUploadEvent event) throws NamingException,
	IOException {
		
		if(this.propImageList.size() < 6)
		{
			InitialContext ctx = new InitialContext();
			PropertyBeanRemote propRe = (PropertyBeanRemote) ctx
					.lookup("MySweetHome/PropertyBean/remote");
			ExternalContext extContext = FacesContext.getCurrentInstance()
			.getExternalContext();
			
			String random_number = RandomStringUtils.randomNumeric(12);
			File result = new File(extContext.getRealPath("//uploaded//PropertyImages//"+ prop.getPropID() + "_"
					+ random_number + "_" + event.getFile().getFileName()));
			this.propImageList.add(result);
			FileOutputStream fileOutputStream = new FileOutputStream(result);
			byte[] buffer = new byte[6124];
			int bulk;
			InputStream inputStream = event.getFile().getInputstream();
			while (true) {
				bulk = inputStream.read(buffer);
				if (bulk < 0) {
					break;
				}
				fileOutputStream.write(buffer, 0, bulk);
				fileOutputStream.flush();
			}
			fileOutputStream.close();
			inputStream.close();
			
			
			this.propImageListLink.add("//uploaded//PropertyImages//"+ prop.getPropID() + "_"
					+ random_number + "_" + event.getFile().getFileName());
			
			Property_Image p_i = new Property_Image();
			p_i.setPath("//uploaded//PropertyImages//"+ prop.getPropID() + "_"
					+ random_number + "_" + event.getFile().getFileName());
			p_i.setProperty(this.prop);
			
			this.propImageListObject.add(p_i);
			propRe.updatePropImages(p_i, this.prop);
			
		} 
		else 
		{
			MessageCall.errorMessage("Number of images limit exceed, you can upload 6 images only !", "image_limit_exceed");
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage(null, new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Error",
					"Number of images limit exceed, you can upload 6 images only !"));
		}
		
		

	}
	
	

}
